﻿using DataChangeTools.WebApi.Common;
using DataChangeTools.WebApi.DTOs;
using DataChangeTools.WebApi.IRepository.IRepositorys;
using DataChangeTools.WebApi.Model;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using System.Security.Cryptography;

namespace DataChangeTools.WebApi.Controllers
{
    [ApiController]
    [Route("/Upgrade/")]
    public class AutoUpdaterController : BasicsController
    {
        private readonly IWebHostEnvironment _webHostEnvironment;
        private IBaseVersionRepository BaseVersionRepository;
        private readonly IFileRepository _fileRepository;
        private readonly ILogger<AutoUpdaterController> _logger;
        public AutoUpdaterController(IBaseVersionRepository baseVersionRepository, IFileRepository fileRepository, IWebHostEnvironment webHostEnvironment, ILogger<AutoUpdaterController> logger)
        {
            _webHostEnvironment = webHostEnvironment;
            _logger = logger;
            BaseVersionRepository = baseVersionRepository;
            thisRepostory = baseVersionRepository;
            _fileRepository = fileRepository;
        }

        #region CRUD

        [HttpPost("Add")]
        public HttpResponseDTO<bool> AddPost(BaseVersionEntity request)
        {
            if (request == null)
            {
                return HttpResponseDTO<bool>.Failure("请求体为空！");
            }
            if (string.IsNullOrEmpty(request.Version))
            {
                return HttpResponseDTO<bool>.Failure("版本号为空！");
            }
            if (string.IsNullOrEmpty(request.UpdateFile))
            {
                return HttpResponseDTO<bool>.Failure("上传文件为空！");
            }

            var List = BaseVersionRepository.GetListByParam(new Dictionary<bool, Dictionary<string, string>>() { { true, new Dictionary<string, string>() { { "Version", request.Version } } } });
            if (List != null)
            {
                var NewList = JsonConvert.DeserializeObject<List<BaseVersionEntity>>(JsonConvert.SerializeObject(List));
                if (NewList.Count > 0)
                {
                    return HttpResponseDTO<bool>.Failure("当前版本号存在，请重新编辑！");
                }

            }
            request.CreateTime = DateTime.Now;
            var result = BaseVersionRepository.Add(request);

            return HttpResponseDTO<bool>.Success(result, "has update.");
        }
        [HttpGet("GetList")]
        public HttpResponseDTO<List<BaseVersionEntity>> GetList()
        {

            List<BaseVersionEntity> model = new List<BaseVersionEntity>();
            var resultList = BaseVersionRepository.GetListByParam(null);
            if (resultList != null)
            {
                model = JsonConvert.DeserializeObject<List<BaseVersionEntity>>(JsonConvert.SerializeObject(resultList));
            }
            model = model.OrderByDescending(t => t.Id).ToList();
            return HttpResponseDTO<List<BaseVersionEntity>>.Success(resultList, "has update.");
        }
        [HttpGet("Delete")]
        public HttpResponseDTO<bool> DeletePost(int Id)
        {
            if (Id <= 0)
            {
                return HttpResponseDTO<bool>.Failure("获取ID为空！");
            }

            var result = BaseVersionRepository.Delete(Id);

            return HttpResponseDTO<bool>.Success(result, "has update.");
        }
        [HttpPost("Update")]
        public HttpResponseDTO<bool> UpdatePost(BaseVersionEntity request)
        {
            if (request == null)
            {
                return HttpResponseDTO<bool>.Failure("请求体为空！");
            }
            if (request.Id <= 0)
            {
                return HttpResponseDTO<bool>.Failure("获取ID为空！");
            }
            if (string.IsNullOrEmpty(request.Version))
            {
                return HttpResponseDTO<bool>.Failure("版本号为空！");
            }
            if (string.IsNullOrEmpty(request.UpdateFile))
            {
                return HttpResponseDTO<bool>.Failure("上传路径为空！");
            }

            var List = BaseVersionRepository.GetListById(request.Id);
            if (List == null)
            {
                return HttpResponseDTO<bool>.Failure("获取当前数据为空！");
            }
            //JObject model = (JObject)JsonConvert.DeserializeObject();

            BaseVersionEntity model = JsonConvert.DeserializeObject<BaseVersionEntity>(JsonConvert.SerializeObject(List));
            request.CreateTime = model.CreateTime;
            var result = BaseVersionRepository.Edit(request);
            System.Text.Json.JsonElement s = new System.Text.Json.JsonElement();
            return HttpResponseDTO<bool>.Success(result, "has update.");
        }

        [HttpGet("GetLastVersion")]
        public HttpResponseDTO<BaseVersionEntity> GetLastVersion()
        {
            var result = BaseVersionRepository.GetLastVserionInfo();
            return HttpResponseDTO<BaseVersionEntity>.Success(result, "has update.");
        }

        #endregion

        [HttpPost("Report")]
        public HttpResponseDTO<bool> ReportPost(ReportDTO request)
        {
            return HttpResponseDTO<bool>.Success(true, "has update.");
        }
        [HttpPost("Check")]
        public HttpResponseDTO<CheckInfoDTO> CheckPost(CheckInfoResDTO info)
        {
            var checkInfo = new CheckInfoDTO()
            {
                OldVserion = info.OldVserion,
                Vserion = info.OldVserion,
                UpdateInfo = "",
            };
            if (info == null)
            {
                return HttpResponseDTO<CheckInfoDTO>.Failure("请求体为空！");
            }
            if (string.IsNullOrEmpty(info.OldVserion))
            {
                return HttpResponseDTO<CheckInfoDTO>.Failure("版本号为空！");
            }

            //获取最新的更具条件 查询最新的
            var NewVersionInfo = BaseVersionRepository.GetLastVserionInfo();

            if (NewVersionInfo == null)
            {
                return HttpResponseDTO<CheckInfoDTO>.Success(checkInfo, "获取成功！");
            }

            checkInfo = new CheckInfoDTO()
            {
                OldVserion = info.OldVserion,
                Vserion = NewVersionInfo.Version,
                UpdateInfo = NewVersionInfo.UpdateInfo,
            };



            Version NewVersion1 = new Version(NewVersionInfo.Version);
            Version OldVserion1 = new Version(info.OldVserion);

            if (NewVersion1.Equals(OldVserion1))
            {
                return HttpResponseDTO<CheckInfoDTO>.Success(checkInfo, "获取成功！");
            }
            if (NewVersion1 > OldVserion1)
            {
                checkInfo.IsNeedUpdate = true;
                //重新获取新版本的信息
                return HttpResponseDTO<CheckInfoDTO>.Success(checkInfo, "有新版本啦！");
            }

            return HttpResponseDTO<CheckInfoDTO>.Success(checkInfo, "获取成功！");
        }
        [HttpPost("Verification")]
        public HttpResponseDTO<IEnumerable<VerificationResultDTO>> VerificationPost(VerifyDTO request)
        {
            var List = new List<VerificationResultDTO>();
            //count++;
            //if (count > 2)
            //{
            //    return HttpResponseDTO<IEnumerable<VerificationResultDTO>>.Success(null, "Upgrade completed.");
            //}
            //获取最新
            //获取最新的更具条件 查询最新的
            var NewVersionList = BaseVersionRepository.GetListByParam(new Dictionary<bool, Dictionary<string, string>> {
                { true,
                    new Dictionary<string, string> {
                        {"IsEnable","1" },
                        {"Platform",request.Platform.ToString() }
                 } }
            });

            if (NewVersionList == null)
            {
                return HttpResponseDTO<IEnumerable<VerificationResultDTO>>.Failure("暂无版本！");
            }
            List<BaseVersionEntity> NewList = JsonConvert.DeserializeObject<List<BaseVersionEntity>>(JsonConvert.SerializeObject(NewVersionList));
            if (NewList.Count <= 0)
            {
                return HttpResponseDTO<IEnumerable<VerificationResultDTO>>.Failure("当前版本,数据存在问题，无法下载！");
            }
            var NewVersionInfo = NewList.OrderByDescending(t => t.CreateTime).FirstOrDefault();
            //var filePath = $"{AppDomain.CurrentDomain.BaseDirectory}\\wwwroot\\{NewVersionInfo.UpdateFile}";
            //var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot", NewVersionInfo.UpdateFile);

            var filePath = $"{AppDomain.CurrentDomain.BaseDirectory}/wwwroot/{NewVersionInfo.UpdateFile}";

            var packet = new FileInfo(filePath);
            ; // 获取 Host
            var result = new List<VerificationResultDTO>
                {
                    new VerificationResultDTO
                    {
                        RecordId = 1,
                        Name = packet.Name.Replace(packet.Extension,""),
                        Hash = FileHelper.GetFileHash(filePath),
                        ReleaseDate =NewVersionInfo.CreateTime,
                        Url = $"{Request.Scheme}://{Request.Host.ToString()}{NewVersionInfo.UpdateFile}",
                        Version = NewVersionInfo.Version,
                        AppType = 1,
                        Platform =  NewVersionInfo.Platform,
                        ProductId = "2d974e2a-31e6-4887-9bb1-b4689e98c77a",
                        IsForcibly = false,
                        Format = packet.Extension,
                        Size = packet.Length,
                        IsFreeze = false
                    }
                };
            return HttpResponseDTO<IEnumerable<VerificationResultDTO>>.Success(result, "has update.");
        }





        [HttpPost("UploadFiles")]
        public async Task<HttpResponseDTO<FileDTO>> UpdateFIle([Required] List<IFormFile> file)
        {
            try
            {
                var target = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot", "packages");

                _logger.Log(LogLevel.Information, $"target::::{target}");
                var FileName = await _fileRepository.UploadFile2(file, target);
                var FileModel = new FileDTO
                {
                    Count = file.Count,
                    Size = _fileRepository.SizeConverter(file.Sum(f => f.Length)),
                    Path = $"/packages/{FileName}"
                };
                return HttpResponseDTO<FileDTO>.Success(FileModel, "has update.");

            }
            catch (Exception ex)
            {
                return HttpResponseDTO<FileDTO>.Failure("上传文件失败：\n" + ex.Message);
            }
        }



    }
}
